package org.tao.lightningmq.broker.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.tao.lightningmq.broker.cache.CommonCache;
import org.tao.lightningmq.broker.model.MqTopicModel;
import org.tao.lightningmq.broker.utils.FileContentUtil;
import org.tao.lightningmq.common.constants.BrokerConstants;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author lht
 * @date 2025/1/3 - 16:47
 * @description: mq主题加载器
 */
public class MqTopicLoader {

    private String filePath;

    public void loadProperties() {
        GlobalProperties globalProperties = CommonCache.getGlobalProperties();
        String mqHome = globalProperties.getMqHome();
        filePath = mqHome + "/config/mq-topic.json";
        // 如果filePath不存在，会在該路径下创建一个空文件
        //FileContentUtil.createFile(filePath);
        String fileContent = FileContentUtil.readFromFile(filePath);
        List<MqTopicModel> mqTopicModels = JSON.parseArray(fileContent, MqTopicModel.class);
        CommonCache.setTopicModelList(mqTopicModels);
    }

    public void startRefreshMqTopicInfoTask() {
        CommonThreadPoolConfig.setRefreshMqTopicTask(() -> {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(BrokerConstants.DEFAULT_REFRESH_MQ_TOPIC_TIME_STEP);
                    List<MqTopicModel> topicModelList = CommonCache.getTopicModelList();
                    FileContentUtil.writeToFile(filePath, JSON.toJSONString(topicModelList, JSONWriter.Feature.PrettyFormat));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
